home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 25 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: hobbes.sco.COM!md
  2. From: md@sco.COM (Michael Davidson)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: "#define" versus "const"
  5. Date: 1 Jan 1996 00:48:26 GMT
  6. Organization: The Santa Cruz Operation, Inc.
  7. Message-ID: <4c7b0q$7d6@hobbes.sco.COM>
  8. References: <4b97mt$rgp@wumpus.cc.uow.edu.au> <Crawford.819482696@voyager>
  9. NNTP-Posting-Host: execsrvr.research.sco.com
  10. Cc: 
  11.  
  12.  
  13. In article <Crawford.819482696@voyager>, CRAWFORD <crawford@iac.net> wrote:
  14. >tp86@wumpus.cc.uow.edu.au (PAOPENG THEERADECH) writes:
  15. >>     Could anybody here tell me what different between "#define" and "const"?.
  16. >>I saw "#define" is a normally use in C program, how about "const", what wrong
  17. >>with "const" and what the advantage of "#define" and disadvantage of "const"?.
  18. >
  19. >    I've always heard that constants allow for better type
  20. >checking.
  21. >
  22.  
  23. By "constants" I assume that you mean "variables which are declared to
  24. be const".
  25.  
  26. Yes, they do allow better type checking and, for that reason, should
  27. be used when it is possible to do so.
  28.  
  29. Unfortunately const was a (comparatively) recent addition to C which
  30. was not widely supported prior to the adoption of the ANSI standard
  31. and the semantics of const are less complete in C than one might like.
  32.  
  33. In particular, "const" variables cannot be used in a "constant-expression"
  34. which is required in a number of places in C (to specify array bounds
  35. in a declarator, to specify the value in a "case" statement etc).
  36.  
  37. So, in C, something like ...
  38. #define    BufferSize 1024
  39.  
  40.  ... is usually more useful than ...
  41. const int BufferSize = 1024;
  42.  
  43.  ... since the former allows you to declare an array thus ...
  44. char my_buffer[BufferSize];
  45.  
  46.  ... and the latter does not.
  47.  
  48. C++ does not have these restrictions and it is generally considered
  49. better C++ style to use "const" rather than "#define" in these
  50. circumstances.
  51.